import React, { useEffect, useRef, useState } from 'react';
import { Divider, Popconfirm, Form } from 'antd';
import { ProColumns, EditableProTable, ActionType } from '@ant-design/pro-table';
import TableHint from '@/components/TableHint/Index';
import { history } from 'umi';
import { doDelivery, updateReceiverInfo, updateOrderStatus, getShopInfo1 } from '@/services/shop/api';
import { getLogisticsList } from '@/services/common/api';
import { MsgType, showMsg } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import TakeDialog from './TakeDialog';

const CustomerInfo: React.FC<any> = (props) => {
  const { detail, optCallback, handleDetail } = props
  const [list, setList] = useState<any>([])
  const actionRef = useRef<ActionType>()
  const [logisticsList, setLogisticsList] = useState<{express_code?: string; express_name?: string;}[]>([]);
  const [editUser, setEditUser] = useState<boolean>(false)
  const [form] = Form.useForm();
  const [shopInfo, setShopInfo] = useState({});
  const [showTake, setShowTake] = useState(false); // 确认提货弹窗

  const columns: ProColumns<any>[] = [
    {
      title: detail.ship_method === 'Z' ? '提货人' : '收货人',
      dataIndex: 'receiver',
      width: 80,
      editable: () => {
        return editUser
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项必填项'
            }
          ]
        }
      }
    },
    {
      title: '手机号码',
      dataIndex: 'receiver_mobile',
      width: 100,
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项必填项'
            }
          ]
        }
      },
      editable: () => {
        return editUser
      }
    },
    {
      title: detail.ship_method === 'Z' ? '提货地址' : '收货地址',
      dataIndex: 'receiver_address',
      width: 350,
      editable: () => {
        return editUser
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项必填项'
            }
          ]
        }
      },
      render: (dom, entity) => {
        const { ship_method } = entity
        if (ship_method === 'Z') {
          return shopInfo.take_address;
        }
        return entity.receiver_address
      }
    },
    {
      title: '快递公司',
      dataIndex: 'mail_name',
      valueType: 'select',
      width: 140,
      hideInTable: detail.pay_status !== 'P' || detail.ship_method === 'Z',
      fieldProps: {
        options: logisticsList.map(item => {
          return {
            label: item.express_name,
            value: item.express_code
          }
        }),
        showSearch: true
      },
      editable: () => {
        return !editUser
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项必填项'
            }
          ]
        }
      }
    },
    {
      title: '物流单号',
      dataIndex: 'mail_no',
      hideInTable: detail.pay_status !== 'P' || detail.ship_method === 'Z',
      width: 180,
      editable: () => {
        return !editUser
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项必填项'
            }
          ]
        }
      }
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      width: 150,
      hideInTable: (!(detail.ship_method === 'Z' && detail.order_status === 'S') || (detail.ship_method === 'K' && detail.order_status !== 'P')),
      render: (dom, entity, _, action) => {
        const { order_status, pay_status, ship_method } = entity
        if (ship_method === 'Z' && order_status === 'S') {
          return [
            <PermissionControl key="take" action_id="600604006">
              <a onClick={() => setShowTake(true)}>确认提货</a>
            </PermissionControl>
          ]
        }
        // 待发货
        if (order_status === 'P' && ship_method === 'K') {
          return [
            <PermissionControl  key="modify" action_id="600604007">
              <a onClick={() => {
                setEditUser(true)
                action?.startEditable?.(entity.order_id)
              }}>修改收货人</a>
            </PermissionControl>,
            <PermissionControl key="delivery" action_id="600604008">
              <a onClick={async () => {
                setEditUser(false)
                action?.startEditable?.(entity.order_id)
              }}>订单发货</a>
            </PermissionControl>
          ]
        }
        return []
      }
    }
  ];

  useEffect(() => {
    if (detail.order_id) {
      const item = {
        order_id: detail.order_id,
        receiver: detail.receiver,
        receiver_mobile: detail.receiver_mobile,
        receiver_address: detail.receiver_address,
        mail_name: detail.mail_name,
        mail_no: detail.mail_no,
        pay_status: detail.pay_status,
        order_status: detail.order_status,
        ship_method: detail.ship_method
      }
      setList([item])
    }
    if (detail.ship_method === 'Z') {
      fetchShopInfo();
    }
  }, [detail])

  // 获取店铺信息
  const fetchShopInfo = async () => {
    try {
      const data = await getShopInfo1(detail.order_id)
     setShopInfo(data)
    } catch (error) {
      showMsg(error?.data?.errmsg)
    }
  }

  useEffect(() => {
    getLogisticsList().then((data: { express_code: string; express_name: string;}[]) => {
      setLogisticsList(data);
    })
  }, [])

  return <div className="service-record order-record">
     <div className="header">
        <div className="title">2. {detail.ship_method === 'K' ? '收货人及物流信息' : '提货信息'}</div>
      </div>

      <Divider style={{margin: '10px 0 2px !important'}} />
      
      <EditableProTable<any> 
        bordered 
        actionRef={actionRef}
        rowKey="order_id"
        options={false}
        search={false}
        recordCreatorProps={false}
        tableExtraRender={(_, data) => {
          return ['P'].includes(detail.order_status) && handleDetail?.refund_way && <TableHint 
            text={<div>此订单收到用户待处理的退款申请，请先处理申请；继续订单发货，则退款申请会被拒绝。</div>} 
            actionText="查看退款申请"
            onAction={() => {
              history.push({
                pathname: '/shop/after-sale/refund',
                query: {
                  apply_id: handleDetail?.apply_id,
                  order_id: detail.order_id
                }
              })
            }}
            showAction/>
        }}
        editable={{
          form,
          type: 'single',
          actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
          onSave: async (key, row) => {
            try {
              if (editUser) {
                await updateReceiverInfo({
                  order_id: key as string,
                  receiver: row.receiver,
                  receiver_address: row.receiver_address,
                  receiver_mobile: row.receiver_mobile
                })
              } else {
                await doDelivery({
                  order_id: detail.order_id,
                  mail_id: row.mail_name,
                  mail_name: logisticsList.find(item => item.express_code === row.mail_name)?.express_name as string,
                  mail_no: row.mail_no
                }, true)
              }
              optCallback?.()
            } catch (error) {
              showMsg(error?.data?.errmsg)
            }
          },

          onCancel: async () => {
            form.resetFields();
          }
        }}
        value={list}
        onChange={setList}
        dataSource={list}
        columns={columns} />
      {
      showTake &&
        <TakeDialog
          id={detail.order_id}
          onSubmit={e => {
            setShowTake(false);
            actionRef.current?.reload();
            optCallback?.()
          }}
          onCancel={() => {
            setShowTake(false);
          }}
        />
    }
  </div>
}

export default CustomerInfo;